// +build !windows

package system

import (
	"fmt"
	"net"
)

func LocalIPV4() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String(), nil
			}
		}
	}
	return "", EmptyIPV4Err
}

func IsLocalIP(ip string) (bool, error) {
	addr, _ := net.LookupIP(ip)
	m := make(map[string]net.IP, len(addr))
	for index, ip := range addr {
		m[ip.String()] = addr[index]
	}
	fmt.Println("is local ", m, ip)
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return false, err
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			_, ok := m[ipnet.IP.String()]
			if ok {
				return true, nil
			}
		}
	}
	return false, nil
}
